﻿#region Imports
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using CommonUtilities.Extensions;
#endregion

namespace CommonUtilities.Converters
{
    /// <summary>
    /// Facilitates conversion between <code>System.Boolean</code> and <code>System.Windows.Visibility</code>
    /// </summary>
    public class VisibilityConverter : IValueConverter
    {
        #region IValueConverter Members
        /// <summary>
        /// Converts a <code>System.Boolean</code> value into <code>System.Windows.Visibility</code>
        /// </summary>
        /// <param name="value">Source as <code>System.Boolean</code></param>
        /// <param name="targetType">Type of the target (<code>System.Windows.Visibility</code>)</param>
        /// <param name="parameter">Conversion parameters</param>
        /// <param name="culture">UI culture of thread</param>
        /// <returns><code>System.Boolean</code> value converted to <code>System.Windows.Visibility</code></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool source;
            Visibility result;

            try { source = (bool)value; }
            catch (Exception) { return Visibility.Collapsed; }

            string option = (parameter as string).Coalesce();
            if (option.StartsWith("-")) source = !source;

            if (source) result = Visibility.Visible;
            else result = (option.Trim('-') == "H") ? Visibility.Hidden : Visibility.Collapsed;

            return result;
        }

        /// <summary>
        /// Converts a <code>System.Windows.Visibility</code> value into <code>System.Boolean</code>
        /// </summary>
        /// <param name="value">Source as <code>System.Windows.Visibility</code></param>
        /// <param name="targetType">Type of the target (<code>System.Boolean</code>)</param>
        /// <param name="parameter">Conversion parameters</param>
        /// <param name="culture">UI culture of thread</param>
        /// <returns><code>System.Windows.Visibility</code> value converted to <code>System.Boolean</code></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Visibility source = Visibility.Collapsed;

            try { source = (Visibility)value; }
            catch (Exception) { return Visibility.Collapsed; }

            bool result = (source == Visibility.Visible);

            string option = (parameter as string).Coalesce();
            if (option.StartsWith("-")) result = !result;

            return result;
        }
        #endregion IValueConverter Members
    }
}
